package com.xkstream.client.ui.live;

import android.util.Log;

import com.google.gson.Gson;
import com.xkstream.client.lgim.LgMessage;
import com.xkstream.client.lgim.LgMessageParser;
import com.xkstream.client.utils.LogUtil;

import org.json.JSONException;
import org.json.JSONObject;

import java.lang.ref.WeakReference;
import java.util.concurrent.TimeUnit;

import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.WebSocket;
import okhttp3.WebSocketListener;
import okio.ByteString;

/**
 * Created by xiaoyi on 2017-10-9.
 */

public class LiveWebSocket extends WebSocketListener {
    private final static String TAG = "LiveWebSocket";
    private WebSocket _WebSocket = null;
    private JSONObject _JsonObject = null;

    private Callback callback;

    private LiveWebSocket(Callback listener) {
        callback = listener;
    }

    private volatile static LiveWebSocket mInstances;

    public static LiveWebSocket getDefault(Callback listener) {
        if (mInstances == null) {
            synchronized (LiveWebSocket.class) {
                if (mInstances == null) {
                    mInstances = new LiveWebSocket(listener);
                } else {
                    mInstances.callback = listener;
                }
            }
        } else {
            mInstances.callback = listener;
        }
        return mInstances;
    }


    @Override
    public void onOpen(WebSocket webSocket, Response response) {
        _WebSocket = webSocket;
        Log.e(TAG, "onOpen");
        if (callback != null) {
            callback.onOpen(webSocket, response);
        }
    }

    @Override
    public void onMessage(WebSocket webSocket, String text) {
        Log.e("MESSAGE>>>>>>>", text);
        try {
            _JsonObject = new JSONObject(text);
            LgMessage msg = LgMessageParser.parser(_JsonObject);
            if (callback != null) {
                callback.onReceive(msg);
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void onMessage(WebSocket webSocket, ByteString bytes) {
        Log.e("MESSAGE>>>>>>>", bytes.toString());
    }

    @Override
    public void onClosing(WebSocket webSocket, int code, String reason) {
        LogUtil.e(TAG, "onClosing");
        webSocket.close(1000, null);
        Log.e("Close:", code + reason);
    }

    @Override
    public void onFailure(WebSocket webSocket, Throwable t, Response response) {
        LogUtil.e(TAG, "onFailure  " + "callback =  " + String.valueOf(callback));
        t.printStackTrace();
        if (callback != null) {
            callback.onFailure(webSocket, t, response);
        }
    }

    /**
     * 初始化WebSocket服务器
     */
    private void run() {
        OkHttpClient client = new OkHttpClient.Builder().readTimeout(0, TimeUnit.MILLISECONDS).build();
        Request request = new Request.Builder().url("ws://echo.websocket.org").build();
        client.newWebSocket(request, this);
        client.dispatcher().executorService().shutdown();
    }

    @Override
    public void onClosed(WebSocket webSocket, int code, String reason) {
        LogUtil.e(TAG, "onClosed");
        super.onClosed(webSocket, code, reason);
        if (callback != null) {
            callback.onClosed(webSocket, code, reason);
        }
    }

    /**
     * @param s
     * @return
     */
    public boolean sendMessage(String s) {
        LogUtil.e(TAG, "sendMessage : " + s);
        return _WebSocket.send(s);
    }

    public boolean sendMessage(LgMessage message) {
        return sendMessage(new Gson().toJson(message));
    }

    public void closeWebSocket() {
        if (_WebSocket != null) {
            _WebSocket.close(1000, "主动关闭");
            Log.e("close", "关闭成功");
        }
    }

/*    */

    /**
     * 获取全局的ChatWebSocket类
     *
     * @return ChatWebSocket
     *//*
    public static LiveWebSocket getLiveWebSocket() {
        if (mChatWebSocket == null) {
            mChatWebSocket = new LiveWebSocket();
            mChatWebSocket.run();
        }
        return mChatWebSocket;
    }*/

    public interface Callback {
        void onOpen(WebSocket webSocket, Response response);

        void onClosed(WebSocket webSocket, int code, String reason);

        void onFailure(WebSocket webSocket, Throwable t, Response response);

        void onReceive(LgMessage message);
    }

    public void removeListener() {
        this.callback = null;
    }
}
